import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, register, resetPassword, sendVerificationCode, verifyCode } from '../api/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(null)

  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUser = (userData) => {
    user.value = userData
  }

  const handleLogin = async (credentials) => {
    try {
      const response = await login(credentials)
      if (response.code === 20000) {
        const access_token = response.data.access_token
        setToken(access_token)
        const userIdentifier = credentials.username || credentials.email
        setUser({ username: userIdentifier })
        return Promise.resolve(response)
      } else {
        return Promise.reject({ message: response.message || '登录失败' })
      }
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const handleRegister = async (userData) => {
    try {
      const response = await register(userData)
      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
  }

    // 发送验证码
  const handleSendVerificationCode = async (data) => {
    try {
      const response = await sendVerificationCode(data)
      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 验证验证码
  const handleVerifyCode = async (data) => {
    try {
      const response = await verifyCode(data)
      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 重置密码
  const handleResetPassword = async (data) => {
    try {
      const response = await resetPassword(data)
      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  return {
    token,
    user,
    handleLogin,
    handleRegister,
    logout,
    handleSendVerificationCode,
    handleVerifyCode,
    handleResetPassword
  }
})